package com.whitlock.backend.shiro;

import com.whitlock.backend.entity.TKUser;
import com.whitlock.backend.jwt.JwtToken;
import com.whitlock.backend.jwt.JwtUtil;
import com.whitlock.backend.service.PermisssionService;
import com.whitlock.backend.service.RoleService;
import com.whitlock.backend.service.UserService;
import com.whitlock.backend.util.UserUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.HashSet;
import java.util.stream.Collectors;

/**
 * @author Whitlock
 * @date 2020/7/9   10:39 上午
 */

@Component
public class AuthRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Autowired
    private PermisssionService permisssionService;

    @Autowired
    private RoleService roleService;

    /**
     * 必须重写此方法，不然Shiro会报错
     * @param token
     * @return
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    /**
     * 只有当需要检测用户权限的时候才会调用此方法，例如checkRole,checkPermission之类的
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        TKUser user= UserUtils.getLoginUser();
        //管理员授予所有权限
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        if("admin".equals(user.getUserName())){
            simpleAuthorizationInfo.setRoles(new HashSet(roleService.list().stream().map(tkRole ->
                    tkRole.getRoleName()).collect(Collectors.toList())));
            simpleAuthorizationInfo.setStringPermissions(new HashSet(permisssionService.list().stream().filter(p ->
                    !StringUtils.isEmpty(p.getPermissionValue())).map(tkPermission -> tkPermission.getPermissionValue()).collect(Collectors.toList())));
        }
        return simpleAuthorizationInfo;
    }

    /**
     * 默认使用此方法进行用户名正确与否验证，错误抛出异常即可。
     * @param auth
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
        String token = (String) auth.getCredentials();
        // 解密获得userId，用于和数据库进行对比
        String userId = null;
        try {
            //这里工具类没有处理空指针等异常这里处理一下(这里处理科学一些)
            userId = JwtUtil.getUserId(token);
        } catch (Exception e) {
            throw new AuthenticationException("heard的token拼写错误或者值为空");
        }
        if (StringUtils.isEmpty(userId)) {
            throw new AuthenticationException("token无效");
        }
        TKUser userBean = userService.getById(userId);
        if (userBean == null) {
            throw new AuthenticationException("用户不存在!");
        }
        if (!JwtUtil.verify(token, userId, userBean.getUserPassword())) {
            throw new AuthenticationException("用户名或密码错误(token无效或者与登录者不匹配)!");
        }
        return new SimpleAuthenticationInfo(userBean, token, "auth_realm");
    }
}

